# !/usr/bin/python
# coding=utf-8
import paramiko
import os

host = '10.168.21.38'  # 主机
port = 22  # 端口
username = 'yanggan'  # 用户名
password = 'Admin@9000'  # 密码

def sftp_to_linux(local, remote):
    sf = paramiko.Transport((host, port))
    sf.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(sf)
    try:
        if os.path.isdir(local):  # 判断本地参数是⽬录还是⽂件
            for f in os.listdir(local):  # 遍历本地⽬录
                print(os.path.join(local + f)," to ", os.path.join(remote + f))
                sftp.put(os.path.join(local + f), os.path.join(remote + f))  # 上传⽬录中的⽂件
        else:
            sftp.put(local, remote)  # 上传⽂件
    except :
        print('upload exception:')
    sf.close()


def sftp_to_local(local, remote):
    sf = paramiko.Transport((host, port))
    sf.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(sf)
    try:
        if os.path.isdir(local):  # 判断本地参数是⽬录还是⽂件
            for f in sftp.listdir(remote):  # 遍历远程⽬录
                local_name=os.path.join(local + f)
                remote_name=os.path.join(remote + f)
                sftp.get(os.path.join(remote + f), os.path.join(local + f))  # 下载⽬录中⽂件
        else:
            sftp.get(remote, local)  # 下载⽂件
    except :
        print('download exception:')
    sf.close()


if __name__ == '__main__':
   # filename="test.tar"

    local = f'E:\\PycharmProjects\\nic-development-assistant-master\\uptest\\'  # 本地文件或目录，与远程一致，当前为windows目录格式，window目录中间需要使用双斜线
    remote = f'/home/yanggan/test/'  # 远程文件或目录，与本地一致，当前为linux目录格式
  #  sftp_upload(local, remote)  # 上传
    sftp_to_local(local, remote)